import { writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const PROJECT_ROOT = join(__dirname, '..');

interface GitHubCommit {
    sha: string;
}

async function fetchLatestSHA(): Promise<string> {
    const url = 'https://api.github.com/repos/modelcontextprotocol/modelcontextprotocol/commits?path=schema/draft/schema.ts&per_page=1';

    const response = await fetch(url);
    if (!response.ok) {
        throw new Error(`Failed to fetch commit info: ${response.status} ${response.statusText}`);
    }

    const commits = (await response.json()) as GitHubCommit[];
    if (!commits || commits.length === 0) {
        throw new Error('No commits found');
    }

    return commits[0].sha;
}

async function fetchSpecTypes(sha: string): Promise<string> {
    const url = `https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/${sha}/schema/draft/schema.ts`;

    const response = await fetch(url);
    if (!response.ok) {
        throw new Error(`Failed to fetch spec types: ${response.status} ${response.statusText}`);
    }

    return await response.text();
}

async function main() {
    try {
        // Check if SHA is provided as command line argument
        const providedSHA = process.argv[2];

        let latestSHA: string;
        if (providedSHA) {
            console.log(`Using provided SHA: ${providedSHA}`);
            latestSHA = providedSHA;
        } else {
            console.log('Fetching latest commit SHA...');
            latestSHA = await fetchLatestSHA();
        }

        console.log(`Fetching spec.types.ts from commit: ${latestSHA}`);

        const specContent = await fetchSpecTypes(latestSHA);

        // Read header template
        const headerTemplate = `/**
 * This file is automatically generated from the Model Context Protocol specification.
 *
 * Source: https://github.com/modelcontextprotocol/modelcontextprotocol
 * Pulled from: https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/main/schema/draft/schema.ts
 * Last updated from commit: {SHA}
 *
 * DO NOT EDIT THIS FILE MANUALLY. Changes will be overwritten by automated updates.
 * To update this file, run: npm run fetch:spec-types
 */`;

        const header = headerTemplate.replace('{SHA}', latestSHA);

        // Combine header and content
        const fullContent = header + specContent;

        // Write to file
        const outputPath = join(PROJECT_ROOT, 'src', 'spec.types.ts');
        writeFileSync(outputPath, fullContent, 'utf-8');

        console.log('Successfully updated src/spec.types.ts');
    } catch (error) {
        console.error('Error:', error instanceof Error ? error.message : String(error));
        process.exit(1);
    }
}

main();
